import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Select,
  Cascader,
  Image,
  Modal,
  Popconfirm,
  Row,
  Space,
  Switch,
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect } from 'react';

import { IconButton, Iconify } from '@/components/icon';
import { useCommon } from '@/hooks/common';

import DesignTemplateEditor from './DesignTemplateEditor/DesignTemplateEditor';
import designTemplateEditorStore from './DesignTemplateEditor/designTemplateEditorStore';

export default function DesignListPage() {
  const uri = 'design-template';
  const formParams = {
    name: '',
    id: 0,
    groupId: 0,
    disable: 0,
    label: ''
  };
  const cateName = '模版列表';
  const {
    data = {},
    query,
    ModalPros,
    searchForm,
    onSearchFormReset,
    onCreate,
    onSwitch,
    onSwitchTop,
    onSwitchEdit,
    cateList,
    doDel,
    onSearch,
    handleChange,
  } = useCommon(
    { name: '', groupId: '', disable: '' },
    uri,
    {
      ...formParams,
    },
    'design-template-group',
  );

  const columns: ColumnsType<any> = [
    { title: '名称', dataIndex: 'name', width: 100 },
    { title: '分类名', dataIndex: 'groupName', width: 100 },
    {
      title: '缩略图',
      dataIndex: 'thumb',
      width: 100,
      render: (thumb) => <Image src={thumb} width="100" />,
    },
    {
      title: '状态',
      dataIndex: 'disable',
      align: 'center',
      width: 120,
      render: (disable, record) => (
        <Switch checked={disable === 0} onChange={() => onSwitch(record.id)} />
      ),
    },
    {
      title: '可编辑',
      dataIndex: 'isEdit',
      align: 'center',
      width: 120,
      render: (isEdit, record) => (
        <Switch checked={isEdit === 0} onChange={() => onSwitchEdit(record.id)} />
      ),
    },
    {
      title: '置顶',
      dataIndex: 'isTop',
      align: 'center',
      width: 120,
      render: (isTop, record) => (
        <Switch checked={isTop === 0} onChange={() => onSwitchTop(record.id)} />
      ),
    },
    { title: '创建人', dataIndex: 'createName', align: 'center', width: 60 },
    { title: '更新时间', dataIndex: 'updateTime', align: 'center', width: 180 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton onClick={() => {
            designTemplateEditorStore.set_design_template(record);
          }}>
            <Iconify icon="solar:pen-bold-duotone" size={18} />
          </IconButton>
          <Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doDel(record.id)}
          >
            <IconButton>
              <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
            </IconButton>
          </Popconfirm>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="分类" name="groupId" className="!mb-0">
                <Cascader
                  showSearch
                  options={cateList}
                  fieldNames={{ label: 'name', value: 'id', children: 'sonList' }}
                />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="名称" name="name" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="状态" name="disable" className="!mb-0">
                <Select
                  options={[
                    { label: '全部', value: '' },
                    { label: '已上架', value: 0 },
                    { label: '已下架', value: 1 },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="可编辑" name="isEdit" className="!mb-0">
                <Select
                  options={[
                    { label: '全部', value: '' },
                    { label: '可编辑', value: 0 },
                    { label: '不可编辑', value: 1 },
                  ]}
                />
              </Form.Item>
            </Col>
            {/* <Col span={8} lg={6}>
              <Form.Item<any> label="置顶" name="isTop" className="!mb-0">
                <Select
                  options={[
                    { label: '全部', value: '' },
                    { label: '置顶', value: 0 },
                    { label: '不置顶', value: 1 },
                  ]}
                />
              </Form.Item>
            </Col> */}
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">
            <Button
              type="primary"
              onClick={() =>
                onCreate({
                  ...formParams,
                  parentId: query.parentId,
                  level: query.parentId === 0 ? 1 : 2,
                })
              }
            >
              新增
            </Button>
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} cateList={cateList} />

      {/* 设计模板编辑器弹窗 */}
      <DesignTemplateEditor onOk={ModalPros.onOk}/>

    </Space>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel, cateList }: any) {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({ ...formValue, groupId: [formValue.groupId1, formValue.groupId] });
  }, [formValue, form]);

  const handleOk = () => {
    const params = { ...formValue, ...form.getFieldsValue() };
    if (!params.id) {
      params.groupId = params.groupId[1];
    }
    onOk(params);
  };

  return (
    <Modal
      title={title}
      open={show}
      onOk={() => handleOk()}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any> label="名称" name="name" required>
          <Input />
        </Form.Item>
        <Form.Item<any> label="分类" name="groupId" required>
          <Cascader options={cateList} fieldNames={{ label: 'name', value: 'id', children: 'sonList' }} />
        </Form.Item>
        <Form.Item<any> label="标签" name="label" required>
          <Input />
        </Form.Item>
      </Form>

    </Modal>
  );
}
